package com.mind.customer.handler.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mind.common.enums.DataType;
import com.mind.common.utils.StringUtils;
import com.mind.customer.domain.vo.HandlerData;
import com.mind.customer.domain.vo.HandlerDataResult;
import com.mind.customer.exception.AjObjectNotFoundException;
import com.mind.customer.mapper.AjMapTableMapper;
import com.mind.customer.mapper.AjObjectMapper;
import com.mind.system.domain.AjMapTable;
import com.mind.system.domain.AjObject;
import com.mind.system.domain.vo.Field;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 通用处理器
 */
@Component
public class CommonHandler {
    @Resource
    private AjObjectMapper objectMapper;

    @Resource
    private AjMapTableMapper mapTableMapper;

    /**
     * 从对象列表找出符合
     *
     * @param handlerData
     * @return
     */
    public HandlerDataResult handleData(HandlerData handlerData) throws AjObjectNotFoundException {
        AjObject ajObject = getObject(handlerData.getTicketType(), handlerData.getTickCate(), handlerData.getTickName());

        List<Field> fields = JSONArray.parseArray(ajObject.getFields(), Field.class);
//        fields = fields.stream().filter(field -> StringUtils.isEmpty(field.getTicketType()) || CollectionUtils.contains(Arrays.asList(field.getTicketType().split(",")), handlerData.getTicketType())).collect(Collectors.toList());
        JSONArray result = processField(handlerData.getTicketType(), fields, handlerData.getOriginalData());
        AjObject finalAjObject = ajObject;
        return new HandlerDataResult() {{
            setResult(result);
            setObject(finalAjObject);
        }};
    }

    public AjObject getObject(String ticketType, String cate, String name) throws AjObjectNotFoundException {
        AjObject ajObject = objectMapper.selectObjectByName(ticketType, name);
        if (ajObject == null) {
            ajObject = objectMapper.selectObjectByCate(ticketType, cate);
        }
        if (ajObject == null) {
            String errMsg = String.format("ticketType={%s},cate={%s},name={%s},没有找到符合条件的对象.",ticketType,cate,name);
            throw new AjObjectNotFoundException(errMsg);
        }
        return ajObject;
    }

    /**
     * 根据字段类型读取字段
     *
     * @param fieldType
     * @param jsonObject
     * @param key
     * @return
     */
    public Object get(String fieldType, JSONObject jsonObject, String key) {
        if ("invoiceLine".equals(key)) {
            return getMappingValue(jsonObject.getString(key), "影像发票种类映射表");
        }
        return jsonObject.get(key);
    }

    /**
     * 递归读取字段
     *
     * @param fields
     * @param originalDataArray
     * @return
     */
    public JSONArray processField(String ticketType, List<Field> fields, JSONArray originalDataArray) {
        JSONArray array = new JSONArray();

        for (int i = 0; i < originalDataArray.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            JSONObject originalData = originalDataArray.getJSONObject(i);
            for (Field f : fields) {
                // 只有单据类型为空或该单据类型符合字段的单据类型才进行匹配,否则跳过
                if (!(StringUtils.isEmpty(f.getTicketType()) || Arrays.asList(f.getTicketType().split(",")).contains(ticketType))) {
                    continue;
                }
                String ruleField = f.getRuleDataField();
                if (StringUtils.isNotEmpty(f.getAttachmentDataField())) {
                    ruleField = f.getAttachmentDataField();
                }
                String displayField = f.getRuleDataField();
                String dataType = f.getDataType();

                String[] ruleFields = ruleField.split(",");

                for (String rField : ruleFields) {
                    if (DataType.HEADER.getCode().equals(dataType)) {
                        if (originalData.containsKey(rField ) && originalData.get(rField) != null) {
                            jsonObject.put(displayField, get(f.getFieldType(), originalData, rField));
//                            break;
                        } else if(StringUtils.isNotEmpty(f.getDefaultValue())){
                            jsonObject.put(displayField, f.getDefaultValue());
                        }else{
                            jsonObject.put(displayField, "null");
                        }
                    } else if (DataType.ROW.getCode().equals(dataType)) {
                        if (originalData.containsKey(rField) && originalData.get(rField) != null  && originalData.getJSONArray(rField).size() > 0) {
                            jsonObject.put(displayField, processField(ticketType, f.getChildren(), originalData.getJSONArray(rField)));
                        } else if (f.getChildren().size() > 0) {
                            jsonObject.put(displayField, processField(ticketType, f.getChildren(), new JSONArray(new JSONObject())));
                        }
                    }

                }
            }
            if (originalData.containsKey("fileVo")) {
                jsonObject.put("fileVo", originalData.get("fileVo"));
            }
            array.add(jsonObject);
        }
        return array;
    }

    public Object getMappingValue(String value, String mappingKey) {
        AjMapTable mapTable = mapTableMapper.selectMapTableByName(mappingKey);
        if (StringUtils.isNull(mapTable)) {
            return value;
        }
        String tableObject = mapTable.getTableObject();
        JSONArray array = JSONArray.parse(tableObject);
        for (int i = 0; i < array.size(); i++) {
            JSONObject mapping = array.getJSONObject(i);
            if (value.equals(mapping.get("发票池种类编码"))) {
                return mapping.get("发票类型名称");
            }
        }
        return value;
    }
}
